/**
 * 调试材质流程 - 找出材质创建和绑定的真实路径
 */

console.log('\n🔍 开始调试材质创建流程...\n');

// 1. 监听所有材质创建
const originalMaterialConstructors = {};
['MeshStandardMaterial', 'MeshPhysicalMaterial', 'MeshPhongMaterial', 'MeshLambertMaterial'].forEach(materialType => {
    if (THREE[materialType]) {
        originalMaterialConstructors[materialType] = THREE[materialType];
        THREE[materialType] = function(...args) {
            const material = new originalMaterialConstructors[materialType](...args);
            console.log(`📦 [材质创建] ${materialType}:`, {
                name: material.name,
                color: `RGB(${material.color.r.toFixed(3)}, ${material.color.g.toFixed(3)}, ${material.color.b.toFixed(3)})`,
                transparent: material.transparent,
                alphaTest: material.alphaTest,
                opacity: material.opacity
            });
            
            // 检查是否为暗色透明材质
            const isTransparent = material.transparent || material.alphaTest > 0 || material.opacity < 1;
            const isDark = material.color.r < 0.6 && material.color.g < 0.6 && material.color.b < 0.6;
            
            if (isTransparent && isDark) {
                console.log(`⚠️ [检测到暗色透明材质] ${material.name || '未命名'}`);
                console.trace('材质创建调用栈:');
            }
            
            return material;
        };
    }
});

// 2. 监听材质属性变化
const originalSetRGB = THREE.Color.prototype.setRGB;
THREE.Color.prototype.setRGB = function(r, g, b) {
    const result = originalSetRGB.call(this, r, g, b);
    
    // 如果这个颜色属于某个材质，记录变化
    if (this._material) {
        console.log(`🎨 [颜色变化] 材质: ${this._material.name || '未命名'}, 新颜色: RGB(${r.toFixed(3)}, ${g.toFixed(3)}, ${b.toFixed(3)})`);
    }
    
    return result;
};

// 3. 监听mesh材质绑定
const originalSetMaterial = Object.getOwnPropertyDescriptor(THREE.Mesh.prototype, 'material').set;
Object.defineProperty(THREE.Mesh.prototype, 'material', {
    set: function(material) {
        if (material) {
            console.log(`🔗 [材质绑定] Mesh: ${this.name || '未命名'}, 材质: ${material.name || '未命名'}`);
            console.log(`   材质属性: RGB(${material.color.r.toFixed(3)}, ${material.color.g.toFixed(3)}, ${material.color.b.toFixed(3)}), transparent=${material.transparent}, alphaTest=${material.alphaTest}`);
            
            // 检查是否为暗色透明材质
            const isTransparent = material.transparent || material.alphaTest > 0 || material.opacity < 1;
            const isDark = material.color.r < 0.6 && material.color.g < 0.6 && material.color.b < 0.6;
            
            if (isTransparent && isDark) {
                console.log(`🚨 [材质绑定时发现暗色透明材质] Mesh: ${this.name}, 材质: ${material.name}`);
                
                // 立即修复
                const matName = (material.userData?.materialName || material.name || '').toLowerCase();
                const meshName = (this.name || '').toLowerCase();
                const isRoadLine = matName.includes('马路') || matName.includes('线') || 
                                 meshName.includes('马路') || meshName.includes('线');
                
                console.log(`🔧 [绑定时立即修复] ${isRoadLine ? '马路线' : '其他透明材质'}`);
                
                if (isRoadLine) {
                    material.color.setRGB(3.0, 3.0, 3.0); // 3倍白色
                    material.transparent = false;
                    material.alphaTest = 0.5;
                    material.depthWrite = true;
                    this.renderOrder = 100;
                    console.log(`   🛣️ 马路线修复: 3倍白色`);
                } else {
                    material.color.setRGB(2.0, 2.0, 2.0); // 2倍白色
                    material.transparent = true;
                    material.alphaTest = 0;
                    material.depthWrite = false;
                    this.renderOrder = 999;
                    console.log(`   🌿 其他透明材质修复: 2倍白色`);
                }
                
                material.needsUpdate = true;
                console.log(`   修复后: RGB(${material.color.r.toFixed(3)}, ${material.color.g.toFixed(3)}, ${material.color.b.toFixed(3)})`);
            }
        }
        
        originalSetMaterial.call(this, material);
    },
    get: function() {
        return this._material;
    }
});

// 4. 监听贴图加载
const originalTextureLoad = THREE.TextureLoader.prototype.load;
THREE.TextureLoader.prototype.load = function(url, onLoad, onProgress, onError) {
    console.log(`🖼️ [贴图加载] URL: ${url}`);
    
    return originalTextureLoad.call(this, url, function(texture) {
        console.log(`✅ [贴图加载完成] URL: ${url}`);
        if (onLoad) onLoad(texture);
    }, onProgress, onError);
};

console.log('✅ 材质流程监听已启动');
console.log('现在请重新绑定材质，观察控制台输出...');

// 5. 提供恢复函数
window.restoreMaterialFlow = () => {
    // 恢复原始构造函数
    Object.keys(originalMaterialConstructors).forEach(materialType => {
        THREE[materialType] = originalMaterialConstructors[materialType];
    });
    
    // 恢复原始方法
    THREE.Color.prototype.setRGB = originalSetRGB;
    Object.defineProperty(THREE.Mesh.prototype, 'material', {
        set: originalSetMaterial,
        get: function() { return this._material; }
    });
    THREE.TextureLoader.prototype.load = originalTextureLoad;
    
    console.log('✅ 材质流程监听已恢复');
};

console.log('\n💡 完成调试后，请运行 restoreMaterialFlow() 恢复正常状态');
